#!/sbin/openrc-run

name=azorius
description="Azorius is an ActivityPub link aggregator and comment forum"

extra_stopped_commands="setup upgradedb cleanup"
extra_started_commands="adduser chpass"
description_setup="Initialize a new azorius.db"
description_upgradedb="Upgrade azorius.db to new schema"
description_cleanup="Move old attachments to trash"
description_adduser="Add a new user account"
description_chpass="Change password of user"

: ${data_dir:="/var/lib/azorius"}
: ${view_dir:="/usr/share/webapps/azorius"}
: ${log_file:="/var/log/azorius.log"}
: ${listen_addr:="127.0.0.1:8282"}

command="/usr/bin/azorius"
command_args="
	-datadir $data_dir
	-viewdir $view_dir
	-log $log_file
	$extra_opts
	"
command_background="yes"
command_user="azorius:azorius"
pidfile="/run/${RC_SVCNAME}.pid"

depend() {
	need localmount net
	after firewall
}

fix_perms() {
	checkpath -f -m 0640 -o "$command_user" "$log_file"
	checkpath -d -m 0750 -o "$command_user" "$data_dir"
}

start_pre() {
	fix_perms || return 1

	if [ ! -f "$data_dir/azorius.db" ]; then
		setup || return 1
	fi

	azorius_exec setconfig listenaddr "$listen_addr"
}

setup() {
	local db_file="$data_dir/azorius.db"

	fix_perms || return 1

	if [ -f "$db_file" ]; then
		eerror "$db_file already exists!"
		return 1
	fi

	ebegin "Creating a new database at $db_file"
	azorius_exec init
	eend $?
}

adduser() {
	azorius_exec adduser
}

chpass() {
	read -p "username: " username

	azorius_exec chpass $username
}

upgradedb() {
	fix_perms || return 1

	ebegin "Upgrading the Azorius database"
	azorius_exec upgrade
	eend $?
}

cleanup() {
	fix_perms || return 1

	ebegin "Cleaning up Azorius attachments"
	azorius_exec trash
	eend $?
}

azorius_exec() {
	start-stop-daemon --exec "$command" --user "$command_user" \
		-- $command_args $*
}
